// /cloudfunctions/client-wallpaper-user/index.obj.js
const db = uniCloud.database()
const collection = db.collection('iss-wallpaper-image')
const favoriteCollection = db.collection('iss-wallpaper-favorite')
const downloadCollection = db.collection('iss-wallpaper-download')
const ratingCollection = db.collection('iss-wallpaper-rating')
const ApiResponse = require('iss-api-response')
const ErrorMessage = ApiResponse.ErrorMessage
const commonMixin = require('common-mixin')

module.exports = {
  ...commonMixin,
  
  async getUserInfo() {
	  if (this.userInfo && this.userInfo.uid) {
		  return ApiResponse.success(this.userInfo)
	  } else {
		  return ApiResponse.unauthorized(ErrorMessage.NOT_LOGIN)
	  }
  },
  
    /**
     * 获取我下载的图片列表（分页）
     * @param {number} pageNum 当前页码
     * @param {number} pageSize 每页数量
     * @returns {object} 返回下载记录列表和分页信息
     */
    async getMyDownloads({pageNum = 1, pageSize = 10, onlyCounts = false}) {
      try {
        if (!this.userInfo) {
          return ApiResponse.unauthorized(ErrorMessage.NOT_LOGIN)
        }
        
        const offset = (pageNum - 1) * pageSize
        const userId = this.userInfo.uid
        
        // 获取下载记录
        const downloadRes = await downloadCollection
          .where({
            user_id: userId
          })
          .orderBy('download_time', 'desc')
          .skip(offset)
          .limit(pageSize)
          .get()
        
        // 获取总记录数
        const countRes = await downloadCollection
          .where({
            user_id: userId
          })
          .count()
		// 根据要求仅返回总数，不返回明细
        if(onlyCounts) {
			return ApiResponse.success({
			  list:[],
			  total: countRes.total,
			  pageNum,
			  pageSize
			})
		}
        // 获取关联的图片信息（包含picurl）
        const imageIds = downloadRes.data.map(item => item.wallpaper_id)
        let images = []
        if (imageIds.length > 0) {
          const imageRes = await collection
            .where({
              _id: db.command.in(imageIds)
            })
            .field({
              _id: true,
              picurl: true,
              description: true,
              classid: true,
              createTime: true,
              score: true,
              ratingCount: true
            })
            .get()
          images = imageRes.data
        }
        
        // 合并数据
        const list = downloadRes.data.map(download => {
          const image = images.find(img => img._id === download.wallpaper_id) || {}
          return {
            ...download,
            picurl: image.picurl, // 添加图片URL
            description: image.description, // 图片描述
            classid: image.classid, // 分类ID
            createTime: image.createTime, // 创建时间
            score: image.score, // 评分
            ratingCount: image.ratingCount // 评分人数
          }
        })
        
        return ApiResponse.success({
          list,
          total: countRes.total,
          pageNum,
          pageSize
        })
        
      } catch (e) {
        console.error(ErrorMessage.GET_MY_DOWNLOADS_ERROR, e)
        return ApiResponse.serverError(ErrorMessage.GET_MY_DOWNLOADS_ERROR)
      }
    },
    
    /**
     * 获取我评分的图片列表（分页）
     * @param {number} pageNum 当前页码
     * @param {number} pageSize 每页数量
     * @returns {object} 返回评分记录列表和分页信息
     */
    async getMyRatings({pageNum = 1, pageSize = 10, onlyCounts = false}) {
      try {
        if (!this.userInfo) {
          return ApiResponse.unauthorized(ErrorMessage.NOT_LOGIN)
        }
        
        const offset = (pageNum - 1) * pageSize
        const userId = this.userInfo.uid
        
        // 获取评分记录
        const ratingRes = await ratingCollection
          .where({
            user_id: userId
          })
          .orderBy('update_time', 'desc')
          .skip(offset)
          .limit(pageSize)
          .get()
        
        // 获取总记录数
        const countRes = await ratingCollection
          .where({
            user_id: userId
          })
          .count()
		
		// 根据要求仅返回总数，不返回明细
		if(onlyCounts) {
			return ApiResponse.success({
			  list:[],
			  total: countRes.total,
			  pageNum,
			  pageSize
			})
		}
        
        // 获取关联的图片信息（包含picurl）
        const imageIds = ratingRes.data.map(item => item.wallpaper_id)
        let images = []
        if (imageIds.length > 0) {
          const imageRes = await collection
            .where({
              _id: db.command.in(imageIds)
            })
            .field({
              _id: true,
              picurl: true,
              description: true,
              classid: true,
              createTime: true,
              score: true,
              ratingCount: true
            })
            .get()
          images = imageRes.data
        }
        
        // 合并数据
        const list = ratingRes.data.map(rating => {
          const image = images.find(img => img._id === rating.wallpaper_id) || {}
          return {
            ...rating,
			myscore: rating.score, // 我的评分
            picurl: image.picurl, // 添加图片URL
            description: image.description, // 图片描述
            classid: image.classid, // 分类ID
            createTime: image.createTime, // 创建时间
            score: image.score, // 评分
            ratingCount: image.ratingCount // 评分人数
          }
        })
        
        return ApiResponse.success({
          list,
          total: countRes.total,
          pageNum,
          pageSize
        })
        
      } catch (e) {
        console.error(ErrorMessage.GET_MY_RATINGS_ERROR, e)
        return ApiResponse.serverError(ErrorMessage.GET_MY_RATINGS_ERROR)
      }
    },
    
    /**
     * 获取我收藏的图片列表（分页）
     * @param {number} pageNum 当前页码
     * @param {number} pageSize 每页数量
     * @returns {object} 返回收藏记录列表和分页信息
     */
    async getMyFavorites({pageNum = 1, pageSize = 10, onlyCounts = false}) {
      try {
        if (!this.userInfo) {
          return ApiResponse.unauthorized(ErrorMessage.NOT_LOGIN)
        }
        
        const offset = (pageNum - 1) * pageSize
        const userId = this.userInfo.uid
        
        // 获取收藏记录
        const favoriteRes = await favoriteCollection
          .where({
            user_id: userId
          })
          .orderBy('create_time', 'desc')
          .skip(offset)
          .limit(pageSize)
          .get()
        
        // 获取总记录数
        const countRes = await favoriteCollection
          .where({
            user_id: userId
          })
          .count()
		  
        // 根据要求仅返回总数，不返回明细
        if(onlyCounts) {
        	return ApiResponse.success({
        	  list:[],
        	  total: countRes.total,
        	  pageNum,
        	  pageSize
        	})
        }
		
        // 获取关联的图片信息（包含picurl）
        const imageIds = favoriteRes.data.map(item => item.wallpaper_id)
        let images = []
        if (imageIds.length > 0) {
          const imageRes = await collection
            .where({
              _id: db.command.in(imageIds)
            })
            .field({
              _id: true,
              picurl: true,
              description: true,
              classid: true,
              createTime: true,
              score: true,
              ratingCount: true
            })
            .get()
          images = imageRes.data
        }
        
        // 合并数据
        const list = favoriteRes.data.map(favorite => {
          const image = images.find(img => img._id === favorite.wallpaper_id) || {}
          return {
            ...favorite,
            picurl: image.picurl, // 添加图片URL
            description: image.description, // 图片描述
            classid: image.classid, // 分类ID
            createTime: image.createTime, // 创建时间
            score: image.score, // 评分
            ratingCount: image.ratingCount // 评分人数
          }
        })
        
        return ApiResponse.success({
          list,
          total: countRes.total,
          pageNum,
          pageSize
        })
        
      } catch (e) {
        console.error(ErrorMessage.GET_MY_FAVORITES_ERROR, e)
        return ApiResponse.serverError(ErrorMessage.GET_MY_FAVORITES_ERROR)
      }
    },
  
  /**
   * 根据ID删除下载图片记录
   * @param {string} id 下载记录ID
   * @returns {object} 操作结果
   */
  async deleteDownloadRecord({id}) {
    try {
      if (!this.userInfo) {
        return ApiResponse.unauthorized(ErrorMessage.NOT_LOGIN)
      }
      
      // 检查记录是否存在且属于当前用户
      const recordRes = await downloadCollection.doc(id).get()
      if (recordRes.data.length === 0) {
        return ApiResponse.notFound(ErrorMessage.DOWNLOAD_RECORD_NOT_FOUND)
      }
      
      if (recordRes.data[0].user_id !== this.userInfo.uid) {
        return ApiResponse.forbidden(ErrorMessage.NO_PERMISSION)
      }
      
      // 删除记录
      await downloadCollection.doc(id).remove()
      
      return ApiResponse.success({
        message: '下载记录删除成功'
      })
      
    } catch (e) {
      console.error(ErrorMessage.DELETE_DOWNLOAD_RECORD_ERROR, e)
      return ApiResponse.serverError(ErrorMessage.DELETE_DOWNLOAD_RECORD_ERROR)
    }
  },
  
  /**
   * 根据ID删除图片收藏记录
   * @param {string} id 收藏记录ID
   * @returns {object} 操作结果
   */
  async deleteFavoriteRecord({id}) {
    try {
      if (!this.userInfo) {
        return ApiResponse.unauthorized(ErrorMessage.NOT_LOGIN)
      }
      
      // 检查记录是否存在且属于当前用户
      const recordRes = await favoriteCollection.doc(id).get()
      if (recordRes.data.length === 0) {
        return ApiResponse.notFound(ErrorMessage.FAVORITE_RECORD_NOT_FOUND)
      }
      
      if (recordRes.data[0].user_id !== this.userInfo.uid) {
        return ApiResponse.forbidden(ErrorMessage.NO_PERMISSION)
      }
      
      // 删除记录
      await favoriteCollection.doc(id).remove()
      
      return ApiResponse.success({
        message: '收藏记录删除成功'
      })
      
    } catch (e) {
      console.error(ErrorMessage.DELETE_FAVORITE_RECORD_ERROR, e)
      return ApiResponse.serverError(ErrorMessage.DELETE_FAVORITE_RECORD_ERROR)
    }
  },
  
  /**
   * 根据ID删除图片评分记录
   * @param {string} id 评分记录ID
   * @returns {object} 操作结果
   */
  async deleteRatingRecord({id}) {
    try {
      if (!this.userInfo) {
        return ApiResponse.unauthorized(ErrorMessage.NOT_LOGIN)
      }
      
      // 检查记录是否存在且属于当前用户
      const recordRes = await ratingCollection.doc(id).get()
      if (recordRes.data.length === 0) {
        return ApiResponse.notFound(ErrorMessage.RATING_RECORD_NOT_FOUND)
      }
      
      if (recordRes.data[0].user_id !== this.userInfo.uid) {
        return ApiResponse.forbidden(ErrorMessage.NO_PERMISSION)
      }
      
      const wallpaperId = recordRes.data[0].wallpaper_id
      
      // 删除记录
      await ratingCollection.doc(id).remove()
      
      // 重新计算该壁纸的平均评分
      const aggregateRes = await ratingCollection.aggregate()
        .match({
          wallpaper_id: wallpaperId
        })
        .group({
          _id: wallpaperId,
          averageScore: { $avg: '$score' },
          ratingCount: { $sum: 1 }
        })
        .end()
      
      if (aggregateRes.data.length > 0) {
        const { averageScore, ratingCount } = aggregateRes.data[0]
        const avgScore = parseFloat(averageScore.toFixed(1))
        
        // 更新壁纸表中的评分
        await collection.doc(wallpaperId).update({
          score: avgScore,
          ratingCount: ratingCount
        })
      } else {
        // 如果没有评分了，重置为默认值
        await collection.doc(wallpaperId).update({
          score: 5,
          ratingCount: 0
        })
      }
      
      return ApiResponse.success({
        message: '评分记录删除成功'
      })
      
    } catch (e) {
      console.error(ErrorMessage.DELETE_RATING_RECORD_ERROR, e)
      return ApiResponse.serverError(ErrorMessage.DELETE_RATING_RECORD_ERROR)
    }
  }
}